package com.ruoyi.sms.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.bizsys.domain.SmsTask;
import com.ruoyi.bizsys.domain.SmsTemplate;
import com.ruoyi.bizsys.service.ISmsSendLogService;
import com.ruoyi.bizsys.service.ISmsTemplateService;
import com.ruoyi.bizsys.service.IVerifyCodeLogService;
import com.ruoyi.sms.common.SmsUtil;
import com.ruoyi.sms.config.SmsConfigTool;
import com.ruoyi.sms.config.SmsSendConfig;
import com.ruoyi.sms.config.VerifyCodeConfigTool;
import com.ruoyi.sms.domain.SmsSendData;
import com.ruoyi.sms.mapper.SmsSendMapper;
import com.ruoyi.sms.service.ISmsService;
import com.ruoyi.sms.util.SmsSignUtil;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.RspEnmu;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDictDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

/**
 * @Author: Jamnsin
 * @Date: 2021/1/13 4:11 下午
 */
@Slf4j
@Service
public class SmsServiceImpl implements ISmsService {

    @Autowired
    SmsConfigTool smsConfig;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    ISmsTemplateService smsTemplateService;

    @Autowired
    ISmsSendLogService smsSendLogService;

    @Autowired
    SmsSendMapper smsMapper;

    @Autowired
    VerifyCodeConfigTool verifyCodeConfig;

    @Autowired
    IVerifyCodeLogService verifyCodeLogService;

    @Autowired
    ISysDictDataService sysDictDataService;

    public static String PARAM_MARK = "#";

    /**
     * 短信发送工具类
     */
    private SmsUtil smsUtil = new SmsUtil();

    private SmsSignUtil smsSignUtil = new SmsSignUtil();

    @Autowired
    SmsSendConfig smsSendConfig;

    /**
     * 短信发送同步方法，需要异步发送请移步 AsyncService.sendSms
     * @param smsData
     * @return
     */
    @Override
    public int sendSms(SmsSendData smsData) {
        int responseCode = -1;
        if (codeSwitch()) {
            log.info("mock开启，模拟的短信内容为：{}", smsData.getContent());
            return 200;
        }
        if (StringUtils.isBlank(smsData.getContent())) {
            String content = this.getSmsContnet(smsData);
            smsData.setContent(content);
        }
        log.info("将要发送的短信内容为：{}", smsData.getContent());

        //发送短信规则
//        SmsAreaNumberConfigVO smsAreaNumberConfig = smsMapper.getSmsAreaNumberConfig(smsData.getPhoneNumber().substring(0, 4));
//        return super.sendSMSImpl(smsData, smsAreaNumberConfig);
        try {
//            responseCode = sendSmsByRule(smsData);
            JSONObject jsonObject = smsSignUtil.encryptBASE64();
            JSONObject data = new JSONObject();
            data.put("phoneNumber",smsData.getPhoneNumber());
            data.put("noticeType",smsData.getNoticeType());
            data.put("verifyCode",smsData.getVerifyCode());
            data.put("content",smsData.getContent());
            data.put("smsType",smsData.getSmsType());
            data.put("smsParam",smsData.getSmsParam());
            data.put("templateId",smsData.getTmplateId());
            jsonObject.put("data",data);
            String result = smsUtil.sendPost(smsSendConfig.getSendSms(),jsonObject, null);
            log.info("--------- send sms  :" + result);
            JSONObject json = JSONObject.parseObject(result);
            if(null != json && json.containsKey("code")){
                responseCode = json.getInteger("code");
            }
        }catch (Exception e) {
            throw new BusinessException(RspEnmu.SMS_SEND_FAIL);
        }
        return responseCode;
    }

    private boolean codeSwitch() {
        return Integer.valueOf(getDictLable("biz_switch", "verify_code_mock")) == 1;
    }
    protected String getDictLable(String dictType, String dictValue) {
        return sysDictDataService.selectDictLabel(dictType, dictValue);
    }

    public String getSmsContnet(SmsSendData smsData) {
        SmsTemplate smsTemplate = new SmsTemplate();
        smsTemplate.setNoticeType(smsData.getNoticeType());
        smsTemplate.setSmsType(smsData.getSmsType());
        smsTemplate.setState("1");
        List<SmsTemplate> smsTemplateList = smsTemplateService.selectSmsTemplateList(smsTemplate);
        String content = smsTemplateList.get(0).getTemplateContent();

        if (content.contains(PARAM_MARK)) {
            content = replaceTemplateParams(content, smsData.getSmsParam());
        }

        return content;
    }

    protected String replaceTemplateParams(String templateContent, JSONObject dataJson) {
        String smsContent = templateContent;

        Iterator<String> iterator = (Iterator<String>) dataJson.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            String value = dataJson.getString(key);
            if (smsContent.contains(key)) {
                smsContent = smsContent.replace(PARAM_MARK + key + PARAM_MARK, value);
            }
        }
        return smsContent;
    }

    /**
     * 批量短信发送
     * @param smsTaskList
     */
    @Override
    public void sendBatchSms(List<SmsTask> smsTaskList) {
        try {
            JSONObject jsonObject = smsSignUtil.encryptBASE64();
            JSONArray jsonArray = new JSONArray();
            for(int i=0; i<smsTaskList.size(); i++){
                SmsTask smsTask = smsTaskList.get(i);
                JSONObject json = new JSONObject();
                json.put("phoneNumber",smsTask.getPhone());
                json.put("noticeType",smsTask.getNoticeType());
                json.put("content",smsTask.getContent());
                json.put("smsType",smsTask.getSmsType());
                json.put("smsParam",smsTask.getSmsParam());
                json.put("templateId",smsTask.getTemplateId());
                jsonArray.add(json);
            }
            jsonObject.put("data",jsonArray);
            String result = smsUtil.sendPost(smsSendConfig.getBatchSendSms(),jsonObject, null);
            log.info("--------- batch send sms  :" + result);
        }catch (Exception e) {
            throw new BusinessException(RspEnmu.SMS_SEND_FAIL);
        }
    }

}

